package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.service.OrdersService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private OrderDetailMapper detailMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    /**
     * 用户下单
     * @param dto
     */
    @Transactional  //0.开启事务
    public OrderSubmitVO submit(OrdersSubmitDTO dto) {
        //获取当前登陆人id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //获取地址（根据地址id查询）
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());
        if (addressBook == null) {
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //获取购物车列表数据（根据用户id查询当前登陆人的购物车数据）
        List<ShoppingCart> cartList = shoppingCartMapper.getByUserId(userId);
        if (cartList == null || cartList.isEmpty()) {
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }


        //1. 构造订单基本数据，存入orders表
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto, orders);
        //1.1 需要补充其他字段数据
        orders.setNumber(String.valueOf(System.currentTimeMillis()));       //订单号
        orders.setStatus(Orders.PENDING_PAYMENT);                           //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款
        orders.setUserId(userId);                                           //用户id
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayMethod(1);                         //支付方式 1微信，2支付宝
        orders.setPayStatus(Orders.UN_PAID);            //支付状态 0未支付 1已支付 2退款
        orders.setPhone(addressBook.getPhone());        //收货人手机号
        orders.setAddress(addressBook.getDetail());     //收货地址
        orders.setUserName(user.getName());                 //下单人
        orders.setConsignee(addressBook.getConsignee());    //收货人
        //1.2 插入数据到表中
        ordersMapper.insert(orders);
        log.info("订单id: {}", orders.getId());

        //2.构造订单明细数据，存入order_detail表
        //注意：订单明细数据其实就是从购物车中取出商品数据存入明细表中
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart shoppingCart : cartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail, "id");
            //补充orderId
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        detailMapper.insertBatch(orderDetailList);

        //3.清空购物车
        shoppingCartMapper.deleteByUserId(userId);

        //4.封装OrderSubmitVO数据，并返回
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // // 当前登录用户id
        // Long userId = BaseContext.getCurrentId();
        // User user = userMapper.getById(userId);
        //
        // //调用微信支付接口，生成预支付交易单
        // JSONObject jsonObject = weChatPayUtil.pay(
        //         ordersPaymentDTO.getOrderNumber(), //商户订单号
        //         new BigDecimal(0.01), //支付金额，单位 元
        //         "苍穹外卖订单", //商品描述
        //         user.getOpenid() //微信用户的openid
        // );
        //
        // if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
        //     throw new OrderBusinessException("该订单已支付");
        // }
        //
        // OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        // vo.setPackageStr(jsonObject.getString("package"));

        // 由于没有匹配的商户id，所以微信支付并不能调用成功，为了模拟成功的结果，所以直接返回成功结果。但是，需要修改订单状态
        // 订单状态：修改为待接单、支付状态：修改为已支付
        paySuccess(ordersPaymentDTO.getOrderNumber());

        return new OrderPaymentVO();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo 订单号
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)         //订单状态：修改为待接单
                .payStatus(Orders.PAID)                 //支付状态：修改为已支付
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);
    }
}
